package cn.yeziji.forum.listener.mq;

import cn.yeziji.forum.basic.netty.user.UserMessage;
import cn.yeziji.forum.common.key.RabbitMQConfig;
import cn.yeziji.forum.common.key.UserCacheKey;
import cn.yeziji.forum.common.key.generate.UserCacheKeyGenerate;
import cn.yeziji.forum.utils.CacheUtils;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户信息监听
 *
 * @author gzkemays
 * @since 2022/11/08 10:19 PM
 */
@Component
@RabbitListener(queuesToDeclare = @Queue(RabbitMQConfig.USER_MSG))
public class UserMessageListener {
  @Resource CacheUtils cache;

  @RabbitHandler
  public void userMessage(UserMessage message) {
    // 用户登出
    if (!message.isFlag()) {
      System.out.println("用户登出消费 -> " + message);
      UserCacheKeyGenerate generate = UserCacheKey.GENERATE;
      String secondaryTokenKey = generate.getSecondaryTokenKey(message.getUsername());
      Object token = cache.get(secondaryTokenKey);
      // token != null 说明 redis 中令牌没过期
      if (token != null) {
        cache.remove(secondaryTokenKey);
        cache.remove(generate.getTokenCacheKey(token.toString()));
      }
    } else {
      System.out.println("用户登录消费 -> " + message);
    }
  }
}
